const dgram = require('dgram');
class UdpServer {
    static _EventCallBack={};
    static ClientMap={};

    constructor() {
        this.server = dgram.createSocket('udp4');
        this.remotePort=0;
        this.remoteIp=0;
        this.port=0;
        this.install();
    }

    set(url, callback) {
        UdpServer._EventCallBack[url]=callback;
    }

    listen(port){
        this.port=port;
        this.server.bind(port);

    }
    send(v,remoteIp,remotePort) {

        if(Array.isArray(v)){
            v=new Buffer(v)
        }
        //
        if(remoteIp){
            this.server.send(v,this.remotePort,this.remoteIp)
        }else {
            let clientKeyList=Object.keys(UdpServer.ClientMap);
            for (let i=0;i<clientKeyList.length;i++) {
                let clientId=clientKeyList[i];
                 let {ip,port,time}= UdpServer.ClientMap[clientId];
                 //100s
                 if(Date.now()-time>100000){
                     delete UdpServer.ClientMap[clientId];
                 }else {
                     this.server.send(v,port,ip);
                 }
            }
        }

    }

    install(app,server){
        let that=this;
        this.server.on('close',()=>{
            UdpServer._EventCallBack['close']? UdpServer._EventCallBack['close']():console.log('udp close');
        });

        this.server.on('error',(err)=>{
            UdpServer._EventCallBack['error']? UdpServer._EventCallBack['error'](): console.log(err);
        });

        this.server.on('listening',()=>{
            UdpServer._EventCallBack['listening']? UdpServer._EventCallBack['listening']():  console.log('udp listen on '+that.port);;

        });
        this.server.on('message',(msg,rinfo)=>{
            that.remoteIp=rinfo.address;
            that.remotePort=rinfo.port;
            let req={}
            req.rinfo=rinfo;
            req.ip=rinfo.address;
            req.port=rinfo.port;
            req.params=msg;
            UdpServer.ClientMap[req.ip+":"+req.port]={time:Date.now(),ip:req.ip,port:req.port}
            let res={};
            res.send=function (v){
                that.server.send(v,req.port,req.ip)
            }
            UdpServer._EventCallBack['message'](req,res)
        });

    }
}

module.exports =  UdpServer;